package com.youxin.logprocess.mysql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 访问mysql数据库
 * 
 * @author yingde.cao
 *
 */
public class DbHelper {
	/**
	 * "jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull&amp;characterEncoding=utf-8";
	 */
	private String url = null;
	public static final String DRIVE_NAME = "com.mysql.jdbc.Driver";
	private String user;
	private String password;

	public Connection conn = null;
	public Statement pst = null;

	public DbHelper(String dbUrl, String user, String password) throws SQLException,ClassNotFoundException{
		this.url = dbUrl;
		this.user = user;
		this.password = password;
		init();
	}

	private void init() throws SQLException, ClassNotFoundException {

		Class.forName(DRIVE_NAME);
		conn = DriverManager.getConnection(url, user, password);

	}

	/**
	 * 执行方法
	 * 
	 * @param sql
	 * @param dbStatement
	 */
	public void execute(IDbStatement dbStatement) {
		try {
			pst = conn.createStatement();
			dbStatement.execute(pst);
		} catch (Exception e) {
		} finally {

		}
	}

	public void close() {
		try {
			if (pst != null) {
				pst.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			if (this.conn != null) {
				this.conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@FunctionalInterface
	public static interface IDbStatement {
		/**
		 * 执行访求
		 * 
		 * @param sqlStatement
		 */
		void execute(Statement sqlStatement);
	}

}